<?php
function log_error($num, $str, $file, $line)
{
    $message = date("Y-m-d H:i:s") . " 文件：{$file},行数：{$line},错误信息：{$str}";
    file_put_contents("../api_resource/logs/" . date("Ymd") . "_callback.log", $message . PHP_EOL, FILE_APPEND);
}
function log_data($params, $channel_code = '', $channel_id = 0)
{
    $message = date("Y-m-d H:i:s") . " 渠道编码：{$channel_code}，ID：{$channel_id}" . "\nGET参数：" . json_encode($_GET) . "\n" . "POST参数:" . json_encode($_POST) . "\n" . ",收到：" . (is_array($params) ? json_encode($params) : $params) . "\n";
    file_put_contents("../api_resource/logs/" . "callback_" . date("Ymd") . ".log", $message . PHP_EOL, FILE_APPEND);
}
set_error_handler("log_error");

include_once '../api_resource/mysql_pdo.php';

include_once '../api_resource/functions.php';


$params = $_GET;


$uri = $_SERVER['REQUEST_URI'];
$uri = str_replace("/callback.php", "", $uri);
if (strpos($uri, "?") !== false) {
    $uri = substr($uri, 0, strpos($uri, '?'));
}

$uri = trim($uri, '/');
$map_uri = explode('/', $uri);

if (count($map_uri) == 2) {
    $channel_code = $map_uri[0] ?? '';
    $channel_id = $map_uri[1] ?? 0;
} else {
    $channel_code = $params['c'] ?? '';
    $channel_id = $params['id'] ?? 0;
}

$method = $_SERVER['REQUEST_METHOD'];
if ($method == 'GET') {
    unset($params['c']);
    unset($params['i']);
    $callback_params = $params;
}
if ($method == 'POST') {
    $callback_params = $_POST;
    if (empty($callback_params)) {
        $callback_params = file_get_contents("php://input");

        $callback_params_arr = json_decode($callback_params, 1);
        if (is_array($callback_params_arr)) {
            $callback_params = $callback_params_arr;
        }
    }
}
log_data($callback_params, $channel_code, $channel_id); //记录回调日志

/*******↓↓↓↓↓↓↓↓↓处理逻辑开始↓↓↓↓↓↓↓↓↓↓*******/
$db = new mysql_pdo();

if (!$channel_code || $channel_id == 0) {
    error('缺少参数');
}

$channel_obj = get_channel_obj($channel_id, $db);

if ($channel_obj->channel_code != $channel_code) {
    error('渠道不匹配');
}

/***************************回调操作*/
$resp = $channel_obj->callback($callback_params);
// print_r($resp);
// exit;
file_put_contents("../api_resource/logs/" . "callback_" . date("Ymd") . ".log", '回调解密数据' . json_encode($resp) . PHP_EOL, FILE_APPEND);

//提交给渠道的订单号
$push_order_sn = $resp['push_order_sn'];

//渠道返回的订单号
$channel_order_sn = $resp['channel_order_sn'];

$order_status = $resp['order_status'];
$msg = substr($resp['msg'], 0, 100);
$resp_data = $resp['resp_data']; //响应给渠道的数据
$resp_code = $resp['code']; //101余额不足
$voucher = $resp['voucher']; //凭证
$callback_data = $resp['params']; //渠道回调的数据

if ($resp['error'] == 1) {
    error($msg);
}
//file_put_contents(  "../api_resource/logs/"."callback".".log", print_r($resp,1) . PHP_EOL, FILE_APPEND );

if ($channel_order_sn && strlen($channel_order_sn) > 1) {
    $channel_order = select_table_one($db, 'cz_channel_order', [
        'channel_order_sn' => $channel_order_sn
    ]);
} else {
    $channel_order = select_table_one($db, 'cz_channel_order', [
        'push_order_sn' => $push_order_sn
    ]);
}
if (!$channel_order) {
    error('订单不存在[QD]');
    //    exit($resp_data);
}
if (in_array(intval($channel_order['channel_order_status']), [3, 4])) {
    error('订单已回调');
    //    exit($resp_data);
}

//匹配订单是否此渠道的
if ($channel_order['channel_id'] != $channel_id) {
    error('回调渠道不匹配');
}

//平台订单号
$order_sn =  $channel_order['order_sn'];
//客户订单
$cz_order = select_table_one($db, 'cz_order', [
    'order_sn' => $order_sn
]);

/***********
//订单超时时间
$cz_order_timeout = $cz_order['timeout'];
$product_id = $cz_order['product_id'];
$spec_id = $cz_order['spec_id'];

$user = select_table_one($db, 'sys_users',[
    'id' => intval($cz_order['create_by'])
]);

$product_info = select_table_one($db, 'cz_product',[
    'id' => $product_id
]);

$spec_info = select_table_one($db, 'cz_spec',[
    'id' => $spec_id
]);
 *********/
if (!$cz_order) {
    //    error('订单不存在[CZ]');
    exit($resp_data);
}

if (in_array(intval($cz_order['order_status']), [3, 4])) {
    //    error('订单结果已完成');
    exit($resp_data);
}

//充值成功 更改渠道订单完成 更改队列完成  更改客户订单完成
if ($order_status == 3) {
    channel_callback_success($db, $channel_order, $cz_order, $msg, $voucher);
    /******
    //更改渠道订单完成
    update_table($db, 'cz_channel_order',[
        'channel_order_status' => 3,
        'msg' => $msg,
        'updated_at' => time()
    ],[
        'id' => $channel_order['id']
    ]);

    //更改队列完成
    update_queue_order_status($db, $cz_order['id'], 3);

    // 更改客户订单完成
    update_cz_order_status($db, $cz_order['id'], 3, $msg);

    //todo 回调客户 回调成功
    sock_queue($cz_order['id'], 'callback_user_order');
     ******/
}
//充值失败 更改渠道订单失败 判断客户订单是否超时等 判断订单是否还有队列 更改队列待
if ($order_status == 4) {
    channel_callback_fail($db, $channel_order, $cz_order, $msg);
    /*******
    //更改渠道订单失败
    update_table($db, 'cz_channel_order',[
        'channel_order_status' => 4,
        'msg' => $msg,
        'updated_at' => time()
    ],[
        'id' => $channel_order['id']
    ]);

    //订单超时(不分产品)
    $is_time_out = $cz_order_timeout > 0 && ($cz_order_timeout - time()) < 0;
    if($is_time_out || $cz_order['is_stop'] == 1){
        //更改队列完成
        update_queue_order_status($db, $cz_order['id'], 3);
        //超时订单不进行拦截
        $product_info['stop_fail'] = 0;
        //订单失败
        order_fail($db, substr(($cz_order['is_stop'] ? "[终止]" : "[超时]").$msg,0,100) , $cz_order, $user, $product_info, $spec_info);
        //todo 回调客户
        exit($resp_data);

    }

    //获取订单队列信息
    $order_queue = select_table_one($db, 'cz_order_queue',[
        'order_id' => $cz_order['id']
    ]);
    if(!$order_queue){
//        error('订单队列不存在');
        exit($resp_data);
    }
    if($order_queue['queue_status'] == 3){
//        error('订单已处理完成');
        exit($resp_data);
    }
    //检查渠道订单是否有处理中的
    $channel_order = select_table_one($db, 'cz_channel_order',[
        'order_sn' => $order_sn,
        'channel_order_status' => ['IN', '(1,2)']
    ]);
    if($channel_order){
//        error('有渠道订单正在处理');
        exit($resp_data);
    }

    $channel_ids = explode(",", $order_queue['channel_queue']);

    $first_channel_id_info = array_shift($channel_ids);
    $channel_id_nums_arr = explode('-', $first_channel_id_info);
    $channel_id = $channel_id_nums_arr[0];
    $channel_nums = $channel_id_nums_arr[1];

    if($channel_id){
        //有渠道 更改队列状态为待处理
        update_queue_order_status($db, $cz_order['id'], 1);

        //继续推送订单
        sock_queue($cz_order['id'], 'push_order');

    }else{
        //没有渠道 判断是否为无限循环
        //todo 以哪个循环判断为准 $order_queue['is_loop']
        if($cz_order['is_loop'] == 0){
            //不是循环订单 渠道跑完了
            //更改队列完成
            update_queue_order_status($db, $cz_order['id'], 3);
            //订单失败
            order_fail($db, $msg, $cz_order, $user, $product_info, $spec_info);
            //todo 回调客户
            exit($resp_data);
        }

        //循环订单
        update_queue_order_status($db, $cz_order['id'],1);
        sock_queue($cz_order['id'], 'queue_order');
    }
     ******/
}

exit($resp_data);
